package com.blast.manager.net.presenter

import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blast.manager.R
import com.blast.manager.adapter.ReadyErrorAdapter
import com.blast.manager.bean.ReadyErrorModel
import com.blast.manager.presenter.CheckLeiGuanAuthPresenter
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.bean.BatteryBean
import com.wxl.common.event.RefreshDataEvent
import com.wxl.common.life.LifecycleManager
import com.wxl.common.life.ViewModelQuick
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.util.DateUtils
import com.wxl.common.util.DeviceUtil
import com.wxl.common.util.ObservableUtil
import com.wxl.common.wiget.ProgressUpdatePop
import kotlinx.android.synthetic.main.layout_net_ready.view.*

class NetCheckReadyPresenter : AbsNetCheckPresenter() {

    val error = arrayListOf<ReadyErrorModel>()
    var mReadyErrorAdapter: ReadyErrorAdapter? = null
    var isInit = true
    var isBlast = false
    var lgTotal = 0
    var mProgressUpdatePop:ProgressUpdatePop?=null
    override fun showView(vararg args: Any) {
        isBlast = args[0] as Boolean
        mProgressUpdatePop =  ProgressUpdatePop.show(context, Runnable {
            ProgressUpdatePop.updateProgress(0,"正在准备中...","准备中",100)
            checkLeiGuan(isBlast)
        })
    }

    private fun checkLeiGuan(isBlast: Boolean) {
        DBHelper.queryLeiGuanEntity(object :
            ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                if (t.isNotEmpty()) {
                    ProgressUpdatePop.updateProgress(1,"正在准备中...","准备中",100)
                    checkDevice(t)
                } else {
                    if (!isBlast) {
                        getActivity().dismissClearAllPop()
                        getActivity().showText(true,"暂无雷管数据。")
                        getActivity().showOnlyBack()
                    } else {
                        getBlastActivity().dismissClearAllPop()
                        getBlastActivity().showText("暂无雷管数据。")
                        getBlastActivity().showOnlyBack()
                    }
                }
            }
        })
    }

    private fun checkDevice(t: List<LeiGuanEntity>) {

        DeviceUtil.updateDeviceTime(context)

        ProgressUpdatePop.updateProgress(2,"正在检查系统信息...","准备中",100)

        rootView.netCheckReadyListView.layoutManager = LinearLayoutManager(context)

        val bb = BatteryBean()

        bb.observe(context as AbsActivity, Observer {
            error.clear()
            it.percent?.let { it1 ->
                if (it1 < 5) {
                    val model = ReadyErrorModel()
                    model.des = "电量仅剩$it1%"
                    model.title = "电量不足"
                    error.add(0, model)
                }
            }
            checkTime(t)
        })
        LifecycleManager.manager.registerLiveData(bb, (context as AbsActivity).lifecycle)
    }

    private fun checkTime(t: List<LeiGuanEntity>) {
        val time = System.currentTimeMillis()
        if (time < DeviceUtil.getDeviceTime()) {
            val model = ReadyErrorModel()
            model.title = "时间异常："
            model.des = DateUtils.getCurrentDate()
            error.add(model)
            DeviceUtil.updateDeviceTime(context)
        } else {
            DeviceUtil.setDeviceTime(time)
        }
        notifyReadyErrorDataChanged(t)
    }


    private fun registerAuthEvent() {
        val event = RefreshDataEvent()
        event.observe(if (!isBlast) getActivity() else getBlastActivity(), Observer {
            if (it.isRefresh) {
                checkAuth()
            }
        })
        LifecycleManager.manager.registerLiveData(
            event,
            (if (!isBlast) getActivity() else getBlastActivity()).lifecycle
        )
    }


    private fun notifyReadyErrorDataChanged(t: List<LeiGuanEntity>) {
        lgTotal = t.size
        if (error.isNotEmpty()) {
            if (mReadyErrorAdapter == null) {
                mReadyErrorAdapter = ReadyErrorAdapter(error)
                rootView.netCheckReadyListView.adapter = mReadyErrorAdapter
            } else {
                mReadyErrorAdapter?.setNewData(error)
            }
            if (!isBlast) {
                getActivity().dismissClearAllPop()
                getActivity().showOnlyBack()
            } else {
                getBlastActivity().dismissClearAllPop()
                getBlastActivity().showOnlyBack()
            }
        } else {
            if (isInit) {
                isInit = false
                registerAuthEvent()
                checkAuth()
            }
        }
    }


    /**
     * 雷管授权检查
     */
    private fun checkAuth() {

        if(mProgressUpdatePop == null || mProgressUpdatePop!!.isDismiss){
            mProgressUpdatePop = ProgressUpdatePop.show(context, Runnable {
                checkAuth()
            })
            return
        }

        ProgressUpdatePop.updateProgress(3,"正在检查授权信息...","准备中",100)

        if (isBlast) {
            getBlastActivity().showText("正在授权验证...")
        }

        ViewModelQuick.observer(
            if (!isBlast) getActivity() else getBlastActivity(),
            CheckLeiGuanAuthPresenter::class.java,
            context,
            object : CheckLeiGuanAuthPresenter.Companion.OnCheckResultCallback {
                override fun onCheckResult(
                    data: List<LeiGuanEntity>,
                    noAuthData: List<LeiGuanEntity>,
                    mTermNum: Int
                ) {
                    if (AppContext.appContext.isCheckModel()) {//打开了单机模式
                        if (!isBlast) {
                            ViewModelQuick.get(getActivity(), NetCheckPortPresenter::class.java)
                                .checkIsDelayPlan(data)
                        } else {
                            getBlastActivity().showText("正在检查延时方案...")
                            ViewModelQuick.get(
                                getBlastActivity(),
                                NetCheckPortPresenter::class.java
                            ).checkIsDelayPlan(data)
                        }
                    } else {
                        if (!isBlast) {
                            //getActivity().dismissClearAllPop()
                        } else {
                            if (mTermNum == -1) {//授权验证失败
                                getBlastActivity().addLog("授权验证", 0, "授权验证失败")
                                getBlastActivity().dismissClearAllPop()
                                getBlastActivity().showText("授权验证失败！")
                                return
                            }
                        }
                        if (noAuthData.isNotEmpty()) {
                            if (!isBlast) {
                                getActivity().addLog("授权验证", 0, "授权验证不匹配")
                                getActivity().show(
                                    NetCheckErrorPresenter::class.java,
                                    noAuthData,
                                    isBlast
                                )
                            } else {
                                getBlastActivity().addLog("授权验证", 0, "授权验证不匹配")
                                getBlastActivity().show(
                                    NetCheckErrorPresenter::class.java,
                                    noAuthData,
                                    isBlast
                                )
                            }
                        } else {
                            if (!isBlast) {
                                ViewModelQuick.get(getActivity(), NetCheckPortPresenter::class.java)
                                    .checkIsDelayPlan(data)
                            } else {
                                getBlastActivity().showTextGone("授权验证成功！正在检查延时方案...")
                                ViewModelQuick.get(
                                    getBlastActivity(),
                                    NetCheckPortPresenter::class.java
                                )
                                    .checkIsDelayPlan(data)
                            }
                        }
                    }
                }
            }, isBlast, if (isBlast) getBlastActivity().isDelayPlan else false
        )
    }


    fun isError(): Boolean {
        return error.isNotEmpty()
    }

    fun getTotal(): Int {
        return lgTotal
    }

    override fun getLayoutResId(): Int {
        return R.layout.layout_net_ready
    }
}